package org.binglan.youziyuepai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.binglan.youziyuepai.entity.PersonalDynamic;
import org.binglan.youziyuepai.entity.PersonalDynamicApply;
import org.binglan.youziyuepai.entity.PersonalDynamicToImage;
import org.binglan.youziyuepai.enums.code.AcceptDatePatConditionEnum;
import org.binglan.youziyuepai.enums.code.CostTypeEnum;
import org.binglan.youziyuepai.enums.code.StatusEnum;
import org.binglan.youziyuepai.exception.MyException;
import org.binglan.youziyuepai.mapper.PersonalDynamicMapper;
import org.binglan.youziyuepai.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.binglan.youziyuepai.utils.EnumUtils;
import org.binglan.youziyuepai.vo.DatePatVo;
import org.binglan.youziyuepai.vo.PageVo;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 个人动态表 服务实现类
 * </p>
 *
 * @author sanjin
 * @since 2019-04-09
 */
@Service
public class PersonalDynamicServiceImpl extends ServiceImpl<PersonalDynamicMapper, PersonalDynamic> implements PersonalDynamicService {

    @Autowired
    ImageService imageService;

    @Autowired
    PhotographyTagService photographyTagService;

    @Autowired
    PersonalDynamicToImageService PersonalDynamicToImageService;

    @Autowired
    UserService userService;

    @Autowired
    OccupationService occupationService;

    @Autowired
    PersonalDynamicApplyService personalDynamicApplyService;


    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean savePersonalDynamic(PersonalDynamic personalDynamic, List<String> imageIds) {

        personalDynamic.setId(Sid.nextShort());
        PersonalDynamicToImageService.saveBatch(imageIds.stream().map(imageId -> {
            PersonalDynamicToImage personalDynamicToImage = new PersonalDynamicToImage();
            personalDynamicToImage.setImageId(imageId);
            personalDynamicToImage.setPersonalDynamicId(personalDynamic.getId());
            return personalDynamicToImage;
        }).collect(Collectors.toList()));
        return this.save(personalDynamic);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<PersonalDynamic> queryPersonalDynamicsByUserId(String userId) {
        PersonalDynamic personalDynamic = new PersonalDynamic();
        personalDynamic.setUserId(userId);
        return list(new QueryWrapper<>(personalDynamic));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Boolean deletePersonalDynamicByPersonalDynamicId(String personalDynamicId, String userId) {
        PersonalDynamic byId = this.getById(personalDynamicId);
        if (byId.getUserId().equals(userId))
            return removeById(personalDynamicId);
        return false;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PageVo<DatePatVo> queryDatePatByPage(Page page, Integer isAllow, Integer occupationId) {
        IPage<PersonalDynamic> personalDynamicIPage = baseMapper.queryDatePatByPage(page, isAllow, occupationId);
        PageVo<DatePatVo> pageVo = new PageVo<>();
        // 总数量
        pageVo.setCount(this.queryCount(isAllow));
        // 当前页码
        pageVo.setCurrent(page.getCurrent());
        // 每页数据量
        pageVo.setSize(page.getSize());
        // 总页数
        pageVo.setTotal(pageVo.getCount() / page.getSize());
        List<PersonalDynamic> records = personalDynamicIPage.getRecords();
        List<DatePatVo> collect = records.stream().map(item -> {
            DatePatVo datePatVo = new DatePatVo();
            datePatVo.setUserVo(userService.queryUserVoByUserId(item.getUserId()));
            BeanUtils.copyProperties(item, datePatVo);
            datePatVo.setCostTypeName(EnumUtils.getMessageByCode(item.getDatePatCondition(),CostTypeEnum.class));
            datePatVo.setDatePatConditionName(EnumUtils.getMessageByCode(item.getDatePatCondition(),AcceptDatePatConditionEnum.class));
            datePatVo.setImages(imageService.queryImageByPersonalDynamicId(item.getId()));

            datePatVo.setOccupation(occupationService.queryOccupationById(item.getOccupationId()));
            return datePatVo;
        }).collect(Collectors.toList());
        pageVo.setRows(collect);
        return pageVo;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public long queryCount(Integer isAllow) {
        PersonalDynamic personalDynamic = new PersonalDynamic();
        personalDynamic.setIsAllow(isAllow);
        return count(new QueryWrapper<>(personalDynamic));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean sendDatePatApply(String userId, String datePatId, String reason) {
        if (StringUtils.isBlank(datePatId)) {
            throw new MyException("datePatId 不能为空");
        }
        // 用户不能给自己的约拍动态发送申请
        PersonalDynamic queryObj = this.queryByPersonalDynamicId(datePatId);
        if(queryObj != null && queryObj.getUserId().equals(userId)) {
            throw new MyException("自己不能给自己的动态发送申请");
        }

        // 保存记录到数据库
        PersonalDynamicApply apply = new PersonalDynamicApply();
        apply.setApplyUserId(userId);
        apply.setPersonalDynamicId(datePatId);
        apply.setReason(reason);
        apply.setStatus(StatusEnum.IGNORE.getCode());
        PersonalDynamicApply save = personalDynamicApplyService.savePersonalDynamicApply(apply);
        return save != null;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PersonalDynamic queryByPersonalDynamicId(String personalDynamicId) {
        return this.getById(personalDynamicId);
    }

}
